
import os
from flask import Blueprint, request, jsonify, render_template, session
from applications.common.utils.http import fail_api, success_api, table_api
from mod import fun
from mod.fun import chklogin, tconf
from plugins.users.libs.bj35api import Bj35Api
from plugins.users.models import User

dir_path = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')

bp = Blueprint('users_index', __name__)

@bp.route("/captcha", methods=['GET'])
def captcha():
    resp, code = fun.init_captcha()
    session["code"] = code
    return resp

@bp.route("/")
@chklogin
def index():
    return 'this is users index'

@bp.route('/profile', methods=['GET'])
def profile():
    return render_template('index/profile.html')


@bp.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        code = request.json.get('captcha')
        if not username or not password:
            return fail_api('用户名或密码不能为空')
        if code.__str__().lower() != session.get('code', None):
            return fail_api('验证码错误')
        session['code'] = None

        userapi = tconf('users','userapi')
        if userapi == 'bj35user':
            userapi = Bj35Api()
            userauth = userapi.auth(username, password)
            if userauth == False:
                return fail_api('用户名或密码错误')
            userinfo = userapi.userinfo(username)
            print(userinfo)
            if userinfo['userAccountControl'] in [514, 546, 66050, 66082]:
                return fail_api('用户被暂停使用')
        elif not userapi or userapi == '':
            userinfo = User.query.filter_by(username=username).first()
            if not userinfo:
                return fail_api('用户不存在')
            if userinfo.status == 0:
                return fail_api('用户被暂停使用')

    else:
        return render_template('index/login.html')